/**
 * 
 */
package org.agiba.xwiki.macro.jira.internal;

import java.util.ArrayList;
import java.util.List;

import org.agiba.xwiki.macro.jira.JiraShortcutMacroParameters;
import org.xwiki.component.annotation.Component;
import org.xwiki.rendering.block.Block;
import org.xwiki.rendering.block.LinkBlock;
import org.xwiki.rendering.block.WordBlock;
import org.xwiki.rendering.listener.Link;
import org.xwiki.rendering.listener.LinkType;
import org.xwiki.rendering.macro.AbstractMacro;
import org.xwiki.rendering.macro.MacroExecutionException;
import org.xwiki.rendering.transformation.MacroTransformationContext;

/**
 * @author kamann
 *
 */
@Component("jira")
public class JiraShortcutMacro extends
		AbstractMacro<JiraShortcutMacroParameters> {
	
	public JiraShortcutMacro(){
		super("jira", "Jira Shortcurt", JiraShortcutMacroParameters.class);
	}

	/* (non-Javadoc)
	 * @see org.xwiki.rendering.macro.Macro#execute(java.lang.Object, java.lang.String, org.xwiki.rendering.transformation.MacroTransformationContext)
	 */
	public List<Block> execute(JiraShortcutMacroParameters parameters, String arg1,
			MacroTransformationContext arg2) throws MacroExecutionException {
		String jiraUrl = (JiraShortcutMacroParameters.JIRA_INSTANCES.get(parameters.getInstance())).url;

		if (!jiraUrl.endsWith("/")){
			jiraUrl = jiraUrl+"/";
		}
		jiraUrl = jiraUrl + "browse/";
		
		Link jiraLink = new Link();
		jiraLink.setReference(jiraUrl+parameters.getIssue());
		jiraLink.setType(LinkType.URI);
		
		WordBlock linkText = new WordBlock("[JIRA:"+parameters.getIssue()+"]");
		
		List<Block> children = new ArrayList<Block>();
		children.add(linkText);
		
		LinkBlock linkBlock = new LinkBlock(children, jiraLink, true);

		List<Block> renderedList = new ArrayList<Block>();
		renderedList.add(linkBlock);
		
		return renderedList;
	}

	/* (non-Javadoc)
	 * @see org.xwiki.rendering.macro.Macro#supportsInlineMode()
	 */
	public boolean supportsInlineMode() {
		return true;
	}

}
